import { defineStore } from 'pinia'
import { ref } from 'vue'
import { setItem, getItem, removeItem } from '@/utils'
import api from '@/api'

export default defineStore('auth', () => {
  const token = ref(getItem('TOKEN'))
  const username = ref('')
  const name = ref('')
  const menuList = ref([])
  const permission = ref([])

  const isLogin = () => {
    return !!token.value
  }

  const login = (user) => {
    token.value = user.token
    username.value = user.username
    name.value = user.name
    permission.value = user.permission
    setItem('TOKEN', token.value)

    // getMenuList()
  }

  const logout = () => {
    token.value = ''
    username.value = ''
    name.value = ''
    permission.value = []
    removeItem('TOKEN')
  }

  const getUserInfo = async () => {
    const res = await api.get('/system/auth/user')
    name.value = res.data.name
    username.value = res.data.username
    permission.value = res.data.permission

    // getMenuList()
  }

  const getMenuList = async () => {
    const res = await api.get('/system/MenuPermissionList')
    // console.log('----menu', res.data)
    var menuArr = res.data
    for (const item of menuArr) {
      if (item.children) {
        for (const items of item.children) {
          // items.push({
          //   component: () => import(items.component)
          // })
          items.component = () => import(items.component)
        }
      }
    }
    console.log('----menu', menuArr)

    menuList.value = menuArr
  }

  return {
    token,
    username,
    name,
    menuList,
    permission,

    isLogin,
    login,
    getUserInfo,
    logout,
    getMenuList,
  }
})
